import { define, watch } from 'cydon'
import { Building } from '../type'
import { CTable } from './CTable'
import { queue } from './QTable'
import { CPagination } from './CPagination'
import { DataFilter } from './DataFilter'
import { processData } from '../util'
import { buildings, terrains } from '../defs'
import { addRecipe, map } from '../game'
import { error } from '@cydon/ui/Message'
import { parseRecipe } from '../recipes'

/**
 * @element building-table
 * 建筑物表格
 */
@define('building-table')
export class BuildingTable extends CTable<Building> {
	static observedAttributes = super.observedAttributes

	/** 选中的块号 */
	selected = -1

	/** 隐藏不可建造 */
	hideUnavailable = true

	connectedCallback() {
		for (const b of buildings) {
			b.recipeId = addRecipe(parseRecipe(b.cost, -1))
		}
		super.connectedCallback()
		watch(this, function (this: BuildingTable) {
			return this.updateContents(this.page, this.filter)
		})
	}

	/** 获取可建造地形 */
	getBuiltOn(val: number) {
		const r = []
		for (let i = 0; i < terrains.length; i++)
			if (val >> i & 1)
				r.push(terrains[i])
		return r.join('/')
	}

	/** 获取背景位置 */
	getBgPos({ id: slot }: Building) {
		return `-${(slot & 15) << 5}px -${(slot >> 4) << 5}px`
	}

	/** 建造 */
	build(b: Building) {
		const slot = this.selected
		if (slot < 0) {
			error('请先选择一个建筑位置')
			return
		}
		const terrain = map[slot * 4] & 7
		if ((b.builtOn >> terrain & 1) == 0) {
			error(`无法在${terrains[terrain]}上建造${b.name}`)
			return
		}
		const level = map[slot * 4 + 3] & 15
		if (level) {
			error('该位置已有建筑')
			return
		}
		queue({
			name: '建造' + b.name,
			desc: '每秒消耗' + b.cost,
			slot,
			remainTime: b.time,
			recipeId: b.recipeId!,
			value: b.id | 1 << 8
		})
	}

	async updateContents(p: CPagination, f?: DataFilter) {
		let list = buildings
		if (this.hideUnavailable) {
			const slot = this.selected
			if (slot >= 0) {
				const flag = 1 << (map[slot * 4] & 7)
				list = list.filter(b => b.builtOn & flag)
			}
			else
				list = []
		}
		this.items = [...processData(list, p, f)]
	}
}

declare global {
	interface HTMLElementTagNameMap {
		'building-table': BuildingTable
	}
}
